using Lzfy_His_Service.Models;
using Lzfy_His_Service.Repositories;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 电脑软件信息管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class PcSoftwareController : ControllerBase
    {
        private readonly IPcSoftwareRepository _pcSoftwareRepository;
        private readonly ILogger<PcSoftwareController> _logger;

        public PcSoftwareController(
            IPcSoftwareRepository pcSoftwareRepository,
            ILogger<PcSoftwareController> logger)
        {
            _pcSoftwareRepository = pcSoftwareRepository;
            _logger = logger;
        }

        /// <summary>
        /// 根据MAC地址查询软件信息
        /// </summary>
        /// <param name="macAddress">MAC地址</param>
        /// <returns>该MAC地址下的所有软件信息</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="404">未找到数据</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("GetByMacAddress")]
        [ProducesResponseType(typeof(ApiResponse<PcSoftwareInfoResponse>), 200)]
        [ProducesResponseType(typeof(ApiResponse<object>), 400)]
        [ProducesResponseType(typeof(ApiResponse<object>), 404)]
        [ProducesResponseType(typeof(ApiResponse<object>), 500)]
        public async Task<IActionResult> GetByMacAddress([FromBody] GetByMacAddressRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .Where(x => x.Value?.Errors.Count > 0)
                        .SelectMany(x => x.Value?.Errors ?? new Microsoft.AspNetCore.Mvc.ModelBinding.ModelErrorCollection())
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new ApiResponse<object> { Success = false, Message = string.Join("; ", errors) });
                }

                if (request?.MacAddress == null)
                {
                    return BadRequest(new ApiResponse<object> { Success = false, Message = "MAC地址不能为空" });
                }

                _logger.LogInformation("开始查询MAC地址 {MacAddress} 的软件信息", request.MacAddress);

                var result = await _pcSoftwareRepository.GetSoftwareByMacAddressAsync(request.MacAddress);
                
                if (result.SoftwareList == null || !result.SoftwareList.Any())
                {
                    _logger.LogWarning("MAC地址 {MacAddress} 未找到软件信息", request.MacAddress);
                    return NotFound(new ApiResponse<object> { Success = false, Message = $"MAC地址 {request.MacAddress} 未找到软件信息" });
                }

                _logger.LogInformation("MAC地址 {MacAddress} 查询到 {Count} 个软件", request.MacAddress, result.TotalCount);
                return Ok(new ApiResponse<PcSoftwareInfoResponse> { Success = true, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询MAC地址 {MacAddress} 软件信息时发生错误", request?.MacAddress);
                return StatusCode(500, new ApiResponse<object> { Success = false, Message = "查询软件信息失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 根据条件查询软件信息（支持分页和筛选）
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <returns>分页的软件信息列表</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("GetByConditions")]
        [ProducesResponseType(typeof(ApiResponse<PagedResult<PcSoftwareInfo>>), 200)]
        [ProducesResponseType(typeof(ApiResponse<object>), 400)]
        [ProducesResponseType(typeof(ApiResponse<object>), 500)]
        public async Task<IActionResult> GetByConditions([FromBody] PcSoftwareQueryRequest request)
        {
            try
            {
                _logger.LogInformation("开始条件查询软件信息，MAC地址: {MacAddress}", request.MACAddress);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new ApiResponse<object> { Success = false, Message = string.Join("; ", errors) });
                }

                var result = await _pcSoftwareRepository.GetSoftwareByConditionsAsync(request);
                
                _logger.LogInformation("条件查询完成，MAC地址: {MacAddress}，总数: {TotalCount}", 
                    request.MACAddress, result.TotalCount);
                
                return Ok(new ApiResponse<PagedResult<PcSoftwareInfo>> { Success = true, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "条件查询软件信息时发生错误，MAC地址: {MacAddress}", request.MACAddress);
                return StatusCode(500, new ApiResponse<object> { Success = false, Message = "查询软件信息失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 获取所有MAC地址列表
        /// </summary>
        /// <returns>MAC地址列表</returns>
        /// <response code="200">查询成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("GetAllMacAddresses")]
        [ProducesResponseType(typeof(ApiResponse<List<string>>), 200)]
        [ProducesResponseType(typeof(ApiResponse<object>), 500)]
        public async Task<IActionResult> GetAllMacAddresses()
        {
            try
            {
                _logger.LogInformation("开始查询所有MAC地址列表");

                var result = await _pcSoftwareRepository.GetAllMacAddressesAsync();
                
                _logger.LogInformation("查询到 {Count} 个MAC地址", result.Count);
                return Ok(new ApiResponse<List<string>> { Success = true, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询MAC地址列表时发生错误");
                return StatusCode(500, new ApiResponse<object> { Success = false, Message = "查询MAC地址列表失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 获取软件统计信息
        /// </summary>
        /// <param name="macAddress">MAC地址</param>
        /// <returns>软件统计信息</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("GetStatistics")]
        [ProducesResponseType(typeof(ApiResponse<object>), 200)]
        [ProducesResponseType(typeof(ApiResponse<object>), 400)]
        [ProducesResponseType(typeof(ApiResponse<object>), 500)]
        public async Task<IActionResult> GetStatistics([FromBody] GetSoftwareStatisticsRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .Where(x => x.Value?.Errors.Count > 0)
                        .SelectMany(x => x.Value?.Errors ?? new Microsoft.AspNetCore.Mvc.ModelBinding.ModelErrorCollection())
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new ApiResponse<object> { Success = false, Message = string.Join("; ", errors) });
                }

                if (request?.MacAddress == null)
                {
                    return BadRequest(new ApiResponse<object> { Success = false, Message = "MAC地址不能为空" });
                }

                _logger.LogInformation("开始查询MAC地址 {MacAddress} 的软件统计信息", request.MacAddress);

                var softwareInfo = await _pcSoftwareRepository.GetSoftwareByMacAddressAsync(request.MacAddress);
                
                var statistics = new
                {
                    MACAddress = request.MacAddress,
                    TotalSoftwareCount = softwareInfo.TotalCount,
                    PublisherCount = softwareInfo.SoftwareList
                        .Where(s => !string.IsNullOrWhiteSpace(s.Publisher))
                        .Select(s => s.Publisher)
                        .Distinct()
                        .Count(),
                    TopPublishers = softwareInfo.SoftwareList
                        .Where(s => !string.IsNullOrWhiteSpace(s.Publisher))
                        .GroupBy(s => s.Publisher)
                        .OrderByDescending(g => g.Count())
                        .Take(10)
                        .Select(g => new { Publisher = g.Key, Count = g.Count() })
                        .ToList(),
                    LastUpdateTime = softwareInfo.LastUpdateTime
                };
                
                _logger.LogInformation("MAC地址 {MacAddress} 统计信息查询完成", request.MacAddress);
                return Ok(new ApiResponse<object> { Success = true, Data = statistics, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询MAC地址 {MacAddress} 统计信息时发生错误", request?.MacAddress);
                return StatusCode(500, new ApiResponse<object> { Success = false, Message = "查询统计信息失败，请稍后重试" });
            }
        }
    }
}